package com.qsl.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qsl.entity.User;
import com.qsl.mapper.UserMapper;
import com.qsl.service.UserService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;

import static com.qsl.constant.Constant.QSL_FANOUT_EXCHANGE;

/**
 * @description: xxx描述
 * @author: 博客园@青石路
 * @date: 2024/1/7 15:48
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private UserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(User user) {
        // 1、更新数据
        boolean updated = this.saveOrUpdate(user);
        // 2、插入操作日志
        // TODO 你们补充插入操作
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                // 3、发消息，通知下游数据更新了
                rabbitTemplate.convertAndSend(QSL_FANOUT_EXCHANGE, null, user.getUserId().toString());
            }
        });
        return updated;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(User user) {
        // 1、更新数据
        boolean updated = this.saveOrUpdate(user);
        // 2、插入操作日志
        // TODO 你们补充插入操作
        return updated;
    }
}
